<?php

class VotePlugin extends Plugin
{
    public $vote = array();

    private $auth;

    public function startup()
    {
        $this->onMessage = array($this, 'getMessage');
        $this->auth = new Auth;
    }

    public function getMessage(Message $message)
    {
        if( preg_match('#^!vote (kick|ban) (.*)$#', $message->getBody(), $matches) )
        {
            array_shift($matches);
            list($type, $nick) = $matches;

            $nick = trim($nick);

            if($nick == $this->getBase()->getRoomNick() )
                return $this->sendMessage('Sorry baby++', $message->getFrom());

            if(!isset( $this->vote[ $nick ] ) )
                $this->vote[$nick] = array();

            if(!isset( $this->vote[ $nick ][ $type ] ) )
                $this->vote[ $nick ][ $type ] = array();

            if( !in_array($message->getJid(), $this->vote[ $nick ][ $type ] ) )
                $this->vote[ $nick ][ $type ][] = $message->getJid();

            if(count($this->vote[ $nick ][ $type ]) == 3)
                if(method_exists($this, 'handle'.$type )){
                     call_user_func(array($this, 'handle'.$type), $nick );
                     $this->vote[ $nick ][ $type ] = array();
                }
        }elseif( preg_match('#^!kick (.*)$#', $message->getBody(), $matches) ){
            if($this->auth->isAllowAction( $message->getJid() , 'kick')){
                $this->handleKick($matches[1]);
            }else{
                $this->sendMessage('You have\'t access.', $message->getFrom());
            }
        }
    }

    public function handleKick($nick, $message = 'Kick! :)')
    {
        $this->getBase()->getConnection()->send(
             '<iq type="set" to="'.$this->getBase()->getRoom().'">'
                .'<query xmlns="http://jabber.org/protocol/muc#admin">'
                    .'<item nick="'.addslashes($nick).'" role="none">'
                        .'<reason>'.$message.'</reason>'
                    .'</item>'
                .'</query>'
            .'</iq>');
        
        $this->sendMessage($nick.' Kicked !');
    }
}

?>